<template>
  <div>
    <el-drawer
      v-model="drawer"
      :with-header="false"
      :modal="false"
      size="382"
      :before-close="closeDrawer"
    >
      <div class="drawer_cont" v-if="dataList.length > 0">
        <div class="flex justify-between items-center box_tit">
          <p>批量操作场次（{{ dataList.length }}）</p>
        </div>
        <div style="height: calc(100vh - 150px); border-bottom: 1px solid #e5e5e5; overflow: auto">
          <div
            class="flex justify-between mt-4 mb-3 mx-4 text-sm"
            v-for="(item, index) in dataList"
            :key="index"
          >
            <p>
              {{ item.siteName }}<span class="ml-2">{{ item.time }}</span>
            </p>
            <p>¥{{ item.price }}</p>
          </div>
        </div>
        <div style="height: 210px; margin-top: 20px" class="overflow-hidden">
          <div class="handle_btn">
            <div>
              <el-button @click="handleUnlockBulletin('batch')" class="primary_btn" key="unlock"
                >解锁场次</el-button
              >
              <el-button type="primary" @click="handleLockBulletin('batch')" key="lock"
                >锁定场次</el-button
              >
            </div>
          </div>
        </div>
      </div>
      <div class="drawer_cont" v-loading="isLoading" v-else>
        <div>
          <div class="flex justify-between items-center box_tit">
            <p>{{ data.siteTypeName }}场地</p>
            <p class="text-custom-blue">金额：¥{{ details.price }}</p>
          </div>
          <template v-if="details.orderType == '0' || details.orderType == '1'">
            <div>
              <div class="px-4 text-sm">
                <div
                  class="flex justify-between items-center mt-4 mb-3"
                  v-for="(item, index) in orderDetailList"
                  :key="index"
                >
                  <p>
                    {{ data.isIndependence == 1 ? '散客' : '' }}{{ item.siteName
                    }}<span class="ml-2">{{
                      data.isIndependence == 1 ? '不限时段' : item.time
                    }}</span>
                  </p>
                  <p>¥{{ item.price }}</p>
                </div>
                <div class="flex justify-between mb-3">
                  <p>小计：</p>
                  <p>¥{{ details.orderMoney }}</p>
                </div>
                <div class="flex justify-between mb-3">
                  <p>优惠券：</p>
                  <p>¥-{{ details.discountAmount }}</p>
                </div>
                <div class="flex justify-between mb-4">
                  <p>实收：</p>
                  <p>¥{{ details.paymentAmount }}</p>
                </div>
              </div>
            </div>
            <div>
              <div class="flex items-center box_tit cursor-pointer" @click="goOrderDetail">
                <p class="text-sm text-custom-blue">订单号：{{ details.orderNo }}</p>
                <img src="@/assets/images/icon/right_blue.png" class="ml-5" />
              </div>
              <div class="px-4 text-sm">
                <div class="mb-3 mt-4">下单时间：{{ details.createTime }}</div>
                <div class="mb-3">支付时间：{{ details.paymentTime }}</div>
                <div class="mb-3">客户姓名：{{ details.nickName }}</div>
                <div class="mb-4">手机号：{{ details.orderPhone }}</div>
              </div>
            </div>
            <div class="user_box">
              <div class="flex items-center box_tit">
                <p>用户</p>
              </div>
              <el-form label-width="84px">
                <el-form-item label="客户姓名：">
                  <el-input v-model="details.nickName" disabled></el-input>
                </el-form-item>
                <el-form-item label="手机号：">
                  <el-input v-model="details.orderPhone" disabled></el-input>
                </el-form-item>
              </el-form>
            </div>
          </template>
          <template v-else>
            <div style="height: calc(100vh - 466px); border-bottom: 1px solid #e5e5e5">
              <div class="flex justify-between mt-4 mb-3 mx-4 text-sm">
                <template v-if="details.isIndependence == 1">
                  <p>散客{{ details.siteName }}<span class="ml-2">不限时段</span></p>
                </template>
                <template v-else>
                  <p>
                    {{ details.siteName }}<span class="ml-2">{{ details.time }}</span>
                  </p>
                </template>
                <p>¥{{ details.price }}</p>
              </div>
              <p class="mx-4 text-sm" v-if="details.orderType == '2'">
                备注： {{ details.remark || '无' }}
              </p>
            </div>
          </template>
        </div>
        <div style="height: 410px" class="overflow-hidden">
          <div class="price_box">
            <p class="text-base mb-5 mt-12" v-if="details.orderType == '2'">当前场次已锁定</p>
            <p class="text-4xl mb-1.5 mt-9" v-else>
              ¥
              {{
                details.orderType == '0' || details.orderType == '2'
                  ? details.orderMoney
                  : details.price
              }}
            </p>
            <span class="text-sm text-color-808080">{{
              details.orderType == '0' || details.orderType == '2' ? '订单金额' : '场地应收'
            }}</span>
          </div>
          <div class="handle_btn">
            <el-button
              type="primary"
              :disabled="details.orderFlag != 8"
              style="width: 100%"
              @click="handleSureOrder"
              >确认场地预约</el-button
            >
            <div>
              <el-button
                :disabled="details.orderFlag != 8"
                @click="handleCancelOrder"
                type="warning"
                >驳回场地预约</el-button
              >
              <el-button
                type="primary"
                :disabled="
                  (details.orderType != '0' && details.orderType != '1') ||
                  details.orderFlag == 8 ||
                  data.isIndependence == 1
                "
                @click="changeBulletin"
                >用户换场</el-button
              >
            </div>
            <div>
              <el-button
                :disabled="
                  details.orderType == '0' || details.orderType == '1' || details.orderType == '2'
                "
                type="primary"
                @click="changePrice"
                >改价</el-button
              >
              <el-button
                v-if="details.orderType == '2'"
                @click="handleUnlockBulletin()"
                class="primary_btn"
                key="unlock"
                :disabled="details.disabled"
                >解锁场次</el-button
              >
              <el-button
                v-else
                :disabled="
                  details.orderType == '0' ||
                  details.orderType == '1' ||
                  details.isIndependence == 1
                "
                type="primary"
                @click="handleLockBulletin()"
                key="lock"
                >锁定场次</el-button
              >
            </div>
          </div>
          <div class="tips_box">
            <p>场馆退款说明</p>
            <p>
              <span>退款时限：{{ stadiumData.cancelHours }}小时</span
              ><span class="ml-3">提前核销时间：{{ stadiumData.writeMinutes }}分钟</span>
            </p>
          </div>
        </div>
      </div>
    </el-drawer>
    <el-dialog
      v-model="dialogVisible"
      title="锁定场次"
      width="28%"
      :show-close="false"
      :append-to-body="true"
      :close-on-click-modal="false"
      v-dialog-drag
    >
      <el-form ref="lockFormRef" :model="lockForm" :rules="rules">
        <el-form-item label="填写备注" prop="remark">
          <el-input type="textarea" v-model="lockForm.remark" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button type="primary" @click="disabledBulletin()">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 修改价格 -->
    <el-dialog
      title="改价"
      v-model="showChangePrice"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
      :showClose="false"
    >
      <el-form ref="priceFormRef" :model="priceForm" label-width="50px" class="mt-8">
        <el-form-item label="价格" prop="price">
          <el-select
            v-model="priceForm.price"
            placeholder="请选择"
            class="input_style"
            style="width: 100%"
          >
            <el-option
              v-for="(item, ind) in priceList"
              :key="ind"
              :label="item.price"
              :value="item.price"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitPrice">确认</el-button>
        <el-button @click="showChangePrice = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 新增/编辑对话框 -->
    <el-dialog
      title="用户换场"
      v-model="showBulletinModal"
      width="554px"
      append-to-body
      :close-on-click-modal="false"
      v-dialog-drag
    >
      <el-form
        ref="bulletinFormRef"
        :model="bulletinForm"
        :rules="bulletinRules"
        label-width="74px"
        class="mt-6"
      >
        <el-form-item label="当前场次">
          <el-select v-model="bulletinForm.bulletinId" placeholder="请选择" class="input_style">
            <el-option
              v-for="item in data.detailVoList"
              :key="item.bulletinId"
              :label="item.siteName + ' ' + item.times"
              :value="item.bulletinId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            placeholder="选择时间"
            v-model="bulletinForm.date"
            type="date"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
            @change="changeBulletinDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-time-select
            placeholder="选择时间"
            v-model="bulletinForm.time"
            :picker-options="timePickerOptions"
          >
          </el-time-select>
        </el-form-item>
        <el-form-item label="场地" prop="siteId">
          <el-select v-model="bulletinForm.siteId" placeholder="请选择" class="input_style">
            <el-option
              v-for="item in siteData.siteList"
              :key="item.siteId"
              :label="item.siteName"
              :value="item.siteId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitBulletin">确定</el-button>
        <el-button @click="closeUpdateBulletin">取消</el-button>
      </div>
    </el-dialog>
    <reject-dialog
      ref="rejectDialogRef"
      :rejectList="rejectList"
      @submit="handleRejectOrder"
    ></reject-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import dayjs from 'dayjs'
import { debounce } from 'lodash'
import {
  disableBulletin,
  updateBulletin,
  disableBulletinList,
  enableBulletinList,
} from '@/api/stadium/stadium'
import {
  getBulletinDetail,
  getOrderDetailToBoard,
  saveBulletin,
  getPriceListByIdAndType,
} from '@/api/site/site'
import rejectDialog from '../common/rejectDialog.vue'
import { cancelOrder, confirmOrder } from '@/api/business/business.js'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'

interface RejectItem {
  id: number
  name: string
}

interface DataItem {
  orderId?: string
  detailVoList?: any[]
  isIndependence?: number
  siteTypeName?: string
  [key: string]: any
}

interface DataListItem {
  bulletinId: string
  siteName: string
  time: string
  price: string
}

interface StadiumData {
  cancelHours?: number
  writeMinutes?: number
  stadiumId?: string
  [key: string]: any
}

interface SiteData {
  siteList?: any[]
  reserveList?: any[]
  [key: string]: any
}

interface OrderDetailItem {
  siteName: string
  time: string
  price: string
  [key: string]: any
}

interface Details {
  bulletinId?: string
  id?: string
  siteId?: string
  siteName?: string
  time?: string
  price?: string
  orderType?: string
  orderMoney?: string
  discountAmount?: string
  paymentAmount?: string
  orderNo?: string
  createTime?: string
  paymentTime?: string
  nickName?: string
  orderPhone?: string
  remark?: string
  isIndependence?: number
  orderFlag?: number
  disabled?: boolean
  bulletinDate?: string
  [key: string]: any
}

interface PriceItem {
  price: string
  [key: string]: any
}

const props = withDefaults(
  defineProps<{
    // drawer: boolean
    data: DataItem
    dataList: DataListItem[]
    stadiumData: StadiumData
    siteData: SiteData
  }>(),
  {
    // drawer: false,
    data: () => ({}),
    dataList: () => [],
    stadiumData: () => ({}),
    siteData: () => ({}),
  },
)
const drawer = defineModel('drawer', { default: false })

const emit = defineEmits<{
  (e: 'close'): void
  (e: 'success'): void
}>()

const router = useRouter()
const store = useStore()

const orderDetailList = ref<OrderDetailItem[]>([])
const details = ref<Details>({})
const dialogVisible = ref(false)
const lockForm = ref({
  remark: '',
})
const rules = ref({
  // remark: [
  //   {
  //     required: true,
  //     message: "请填写备注",
  //     trigger: "blur",
  //   },
  // ],
})
const showChangePrice = ref(false)
const priceForm = ref({
  price: null as string | null,
  date: '',
  time: '',
  stadiumId: '',
  siteId: '',
  id: '',
})
const priceList = ref<PriceItem[]>([])
const isLoading = ref(false)
const rejectList = ref<RejectItem[]>([
  { id: 1, name: '数据未同步，场地被提前占用' },
  { id: 2, name: '系统故障' },
  { id: 3, name: '恶意占单' },
  { id: 4, name: '临时闭馆维修' },
  { id: 5, name: '活动优先占用' },
  { id: 6, name: '时段价格调整' },
  { id: 7, name: '其他原因' },
])
const showBulletinModal = ref(false)
const timePickerOptions = ref({
  step: '00:60',
  start: '',
  end: '',
  minTime: '',
})
const bulletinForm = ref({
  date: null as string | null,
  time: null as string | null,
  siteId: null as string | null,
  orderId: null as string | null,
  bulletinId: null as string | null,
  price: '',
  oldSiteId: '',
})
const bulletinRules = ref({
  date: [
    {
      required: true,
      message: '请选择日期',
      trigger: 'change',
    },
  ],
  time: [
    {
      required: true,
      message: '请选择时间',
      trigger: 'change',
    },
  ],
  siteId: [
    {
      required: true,
      message: '请选择场地',
      trigger: 'change',
    },
  ],
})

const lockFormRef = ref<FormInstance>()
const priceFormRef = ref<FormInstance>()
const bulletinFormRef = ref<FormInstance>()
const rejectDialogRef = ref<InstanceType<typeof rejectDialog>>()

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7
}

const getBulletinDetailFunc = async () => {
  const { data } = await getBulletinDetail({
    bulletinId: details.value.bulletinId,
  })
  details.value = data
  details.value.bulletinId = data.id
}

// 获取预定场次详情
const getOrderDetail = async () => {
  isLoading.value = true
  const { data } = await getOrderDetailToBoard({
    orderId: props.data.orderId,
  })
  orderDetailList.value = data.orderDetailList
  details.value = data.orderDetailVo
  isLoading.value = false
}

// 解锁场次
const handleUnlockBulletin = (type?: string) => {
  ElMessageBox.confirm('是否确认解锁该场次？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const bulletinIds =
        type && type == 'batch'
          ? props.dataList.map((item) => item.bulletinId)
          : details.value.bulletinId
      const res =
        type == 'batch'
          ? await enableBulletinList(bulletinIds)
          : await disableBulletin({
              bulletinId: bulletinIds,
              orderType: '',
            })
      ElMessage.success('操作成功')
      emit('success')
      if (type == 'batch') {
        emit('close')
      } else {
        await getBulletinDetailFunc()
      }
    })
    .catch(() => {})
}

// 锁定场次
const handleLockBulletin = (type?: string) => {
  ElMessageBox.confirm('是否确认锁定该场次？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const bulletinIds =
        type && type == 'batch'
          ? props.dataList.map((item) => item.bulletinId)
          : details.value.bulletinId
      const res =
        type == 'batch'
          ? await disableBulletinList(bulletinIds)
          : await disableBulletin({
              bulletinId: bulletinIds,
              orderType: 2,
            })
      ElMessage.success(res.msg)
    })
    .then(() => {
      emit('success')
      if (type == 'batch') {
        emit('close')
      } else {
        getBulletinDetailFunc()
      }
    })
    .catch(() => {})
}

// 锁定场次/解锁场次
const disabledBulletin = () => {
  if (!lockFormRef.value) return
  lockFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await disableBulletin({
        bulletinId: details.value.bulletinId,
        orderType: 2,
        ...lockForm.value,
      })
      ElMessage.success(res.msg)
      dialogVisible.value = false
      await getBulletinDetailFunc()
      emit('success')
    }
  })
}

// 修改价格
const changePrice = async () => {
  showChangePrice.value = true
  const { data } = await getPriceListByIdAndType({
    id: details.value.siteId,
  })
  priceList.value = data
  priceForm.value = {
    date: details.value.bulletinDate || '',
    time: details.value?.time?.replace(/-/g, ' - ') || '',
    stadiumId: props.stadiumData.stadiumId || '',
    siteId: details.value.siteId || '',
    id: details.value?.bulletinId || '',
    price: null,
  }
}

// 修改价格确定
const submitPrice = async () => {
  if (priceForm.value.price == null) {
    ElMessage.error('请选择价格')
    return
  }
  const res = await saveBulletin(priceForm.value)
  ElMessage.success(res.msg)
  showChangePrice.value = false
  details.value.bulletinId = res.data
  await getBulletinDetailFunc()
  emit('success')
}

// 更换场次选择日期
const changeBulletinDate = () => {
  const today = dayjs(new Date()).format('YYYY-MM-DD')
  bulletinForm.value.time = null
  const now = new Date()
  const nowHour = now.getHours()
  const nowMinute = now.getMinutes()
  if (today == bulletinForm.value.date) {
    timePickerOptions.value.minTime = `${nowHour.toString().padStart(2, '0')}:${nowMinute
      .toString()
      .padStart(2, '0')}`
  } else {
    timePickerOptions.value.minTime = ''
  }
}

// 用户换场
const changeBulletin = () => {
  showBulletinModal.value = true
  nextTick(() => {
    if (bulletinFormRef.value) {
      bulletinFormRef.value.clearValidate()
    }
  })
  if (props.siteData.reserveList && props.siteData.reserveList.length > 0) {
    timePickerOptions.value.start = props.siteData.reserveList[0].time
    timePickerOptions.value.end =
      props.siteData.reserveList[props.siteData.reserveList.length - 1].time
  }
  bulletinForm.value = {
    date: null,
    time: null,
    siteId: null,
    orderId: props.data.orderId || null,
    bulletinId:
      props.data.detailVoList && props.data.detailVoList.length > 0
        ? props.data.detailVoList[0].bulletinId
        : null,
    price: details.value.price || '',
    oldSiteId: details.value.siteId || '',
  }
}

// 提交更改的场地信息
const submitBulletin = debounce(
  async () => {
    if (!bulletinFormRef.value) return
    bulletinFormRef.value.validate(async (valid) => {
      if (valid) {
        const res = await updateBulletin(bulletinForm.value)
        ElMessage.success(res.msg)
        closeUpdateBulletin()
        emit('success')
        emit('close')
        await getOrderDetail()
      }
    })
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 关闭用户换场弹窗
const closeUpdateBulletin = () => {
  nextTick(() => {
    if (bulletinFormRef.value) {
      bulletinFormRef.value.resetFields()
    }
  })
  showBulletinModal.value = false
}

// 商家确认订单
const handleSureOrder = () => {
  ElMessageBox.confirm('是否确认该场地预约？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      return confirmOrder({
        orderId: props.data.orderId,
        userId: store.state.user.id,
      })
    })
    .then(() => {
      emit('success')
      ElMessage.success('操作成功')
      getOrderDetail()
    })
    .catch(() => {})
}

// 商家驳回订单
const handleCancelOrder = () => {
  if (rejectDialogRef.value) {
    rejectDialogRef.value.showRejectModal = true
  }
}

// 商家驳回订单 驳回原因确认
const handleRejectOrder = async (val: string) => {
  const cancelParams = {
    userId: store.state.user.id,
    orderId: props.data.orderId,
    orderRemarks: val,
  }
  await cancelOrder(cancelParams)
  emit('success')
  ElMessage.success('操作成功')
  getOrderDetail()
}

// 跳转订单详情
const goOrderDetail = () => {
  router.push({
    path: '/order/detail',
    query: { id: props.data.orderId },
  })
}

// 关闭
const closeDrawer = () => {
  emit('close')
}

watch(
  () => drawer.value,
  (val) => {
    if (val) {
      if (
        props.data.orderId != undefined &&
        props.data.orderId != '' &&
        props.data.orderId != null
      ) {
        getOrderDetail()
      } else {
        orderDetailList.value = []
        setTimeout(() => {
          details.value = props.data
        }, 100)
      }
    }
  },
  {
    deep: true,
  },
)
</script>

<style lang="scss" scoped>
.drawer_cont {
  color: #383838;
  .box_tit {
    height: 40px;
    background: #f0f5ff;
    padding: 0 16px;
    font-size: 16px;
  }
  .user_box {
    :deep(.el-form) {
      margin: 22px 16px 0;
      border-bottom: 1px solid #e5e5e5;
      .el-input {
        width: 223px;
        &.is-disabled {
          .el-input__inner {
            background: #e5e5e5;
            border-color: #a6a6a6;
            color: #b7b7b7;
          }
        }
      }
      .el-input__inner {
        height: 29px;
        line-height: 29px;
        border-radius: 6px;
      }
      .el-form-item__label {
        line-height: 29px;
      }
      .el-form-item__content {
        height: 29px;
        line-height: 29px;
      }
    }
  }
  .handle_btn {
    padding: 0 16px 9px;
    .el-button {
      width: 170px;
      height: 38px;
      line-height: 38px;
      padding: 0;
      border-radius: 6px;
      margin-bottom: 17px;
      & + .el-button {
        margin-left: 12px;
      }
      &.el-button--warning {
        background: #ff8d1a;
        border-color: #ff8d1a;
      }
      &.is-disabled {
        background: #e5e5e5 !important;
        color: #b3b3b3 !important;
        border-color: #e5e5e5 !important;
      }
      &.primary_btn {
        background: #fff;
        color: #2a82e4;
        border-color: #2a82e4;
        color: #2a82e4;
      }
    }
  }
  .price_box {
    text-align: center;
    padding-bottom: 43px;
    p {
      color: #f64e4e;
    }
  }
  .tips_box {
    height: 100px;
    background: #f0f5ff;
    color: #2a82e4;
    padding: 10px 16px 0;
    box-sizing: border-box;
    font-size: 14px;
    line-height: 21px;
  }
}
:deep(.el-dialog) {
  border-radius: 6px;
  .el-dialog__header {
    border-radius: 6px 6px 0 0;
    background: rgba(243, 244, 246, 1);
    padding: 12px 15px;
    .el-dialog__title {
      font-size: 16px;
      color: #383838;
    }
  }
  .el-dialog__body {
    padding: 0 23px 0 17px;
  }
  .el-dialog__footer {
    padding-top: 7px;
    padding-bottom: 24px;
  }
  .dialog-footer {
    text-align: center;
    .el-button {
      width: 76px;
      height: 32px;
      line-height: 32px;
      border-radius: 6px;
      & + .el-button {
        margin-left: 9px;
      }
    }
  }
  .el-form {
    padding: 0 26px;
    .el-select,
    .el-date-editor {
      width: 100%;
      .el-input__inner {
        border-radius: 6px;
      }
    }
  }
}
